#include <iostream>
#include <thread>
#include <barrier>
#include <vector>

// 回调函数
void on_completion() {
    std::cout << "Barrier is reset. All threads have synchronized their state." << std::endl;
}

int main() {
    const int num_threads = 4;
    std::barrier sync_point(num_threads, on_completion);  // 创建barrier对象，设置需要同步的线程数和回调函数

    auto thread_work = [&sync_point](int thread_id) {
        std::cout << "Thread " << thread_id << " is starting its task." << std::endl;

        // 模拟不同线程工作的不同阶段
        std::this_thread::sleep_for(std::chrono::seconds(1 + thread_id)); // 不同线程可能在不同时间到达

        if (thread_id == 0) {
            // 第一个线程只到达，不等待
            (void)sync_point.arrive();//显式忽略返回值
            std::cout << "Thread " << thread_id << " calls arrive()." << std::endl;
        } else if (thread_id == 1) {
            // 第二个线程到达并立即等待
            sync_point.arrive_and_wait();
            std::cout << "Thread " << thread_id << " calls arrive_and_wait()." << std::endl;
        } else if (thread_id == 2) {
            // 第三个线程到达并使用 token 等待
            auto token = sync_point.arrive();
            sync_point.wait(std::move(token));
            std::cout << "Thread " << thread_id << " calls wait() with token." << std::endl;
        } else if (thread_id == 3) {
            // 第四个线程到达并退出同步机制
            sync_point.arrive_and_drop();
            std::cout << "Thread " << thread_id << " calls arrive_and_drop()." << std::endl;
        }

        // 一些后续工作
        std::cout << "Thread " << thread_id << " completes its task." << std::endl;
    };

    std::vector<std::thread> threads;
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(thread_work, i);
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}